import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useGlobSetting } from '/@/hooks/setting';

const { createMessage, createWarningModal } = useMessage();
const glob = useGlobSetting();

/**
 * 导出文件xlsx的mime-type
 */
export const XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
/**
 * 导出文件xlsx的文件后缀
 */
export const XLSX_FILE_SUFFIX = '.xlsx';

export function useMethods() {
  /**
   * 导出xls
   * @param name
   * @param url
   */
  async function exportXls(name, url, params, isXlsx = false) {
    defHttp.post({ url: url, params: params }, { isTransformResponse: false })
      .then((res) => {
        var href = window.config.base_url + res.data;
        var tempwindow = window.open("_blank"); // 先打开页面
        tempwindow.location = href;
      });
}

/**
 * 导入xls
 * @param data 导入的数据
 * @param url
 * @param success 成功后的回调
 */
async function importXls(data, url, success) {
  const isReturn = (fileInfo) => {
    try {
      if (fileInfo.code === 201) {
        let {
          message,
          result: { msg, fileUrl, fileName },
        } = fileInfo;
        let href = glob.uploadUrl + fileUrl;
        createWarningModal({
          title: message,
          centered: false,
          content: `<div>
                                <span>${msg}</span><br/> 
                                <span>具体详情请<a href = ${href} download = ${fileName}> 点击下载 </a> </span> 
                              </div>`,
        });
        //update-begin---author:wangshuai ---date:20221121  for：[VUEN-2827]导入无权限，提示图标错误------------
      } else if (fileInfo.code === 500 || fileInfo.code === 510) {
        createMessage.error(fileInfo.message || `${data.file.name} 导入失败`);
        //update-end---author:wangshuai ---date:20221121  for：[VUEN-2827]导入无权限，提示图标错误------------
      } else {
        createMessage.success(fileInfo.message || `${data.file.name} 文件上传成功`);
      }
    } catch (error) {
      console.log('导入的数据异常', error);
    } finally {
      typeof success === 'function' ? success(fileInfo) : '';
    }
  };
  await defHttp.uploadFile({ url }, { file: data.file }, { success: isReturn });
}

return {
  handleExportXls: (name: string, url: string, params?: object) => exportXls(name, url, params),
  handleImportXls: (data, url, success) => importXls(data, url, success),
  handleExportXlsx: (name: string, url: string, params?: object) => exportXls(name, url, params, true),
};
}
